package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.annotation.RetryOnFailure;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.exception.OptimisticLockingFailureException;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/19 16:11
 * @Description:预约订单服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	OrderSettingDao orderSettingDao;

	@Autowired
	MemberDao memberDao;

	@Autowired
	OrderDao orderDao;
	
	/**
	 *  @描述：新增预约
	 */
	//使用注解定位切dian
	@RetryOnFailure
	public Result add(Map orderInfo) throws Exception {
		// 获取预约日期
		String orderDate = String.valueOf(orderInfo.get("orderDate"));
		// 字符串转换成Date
		Date date = DateUtils.parseString2Date(orderDate);
		// 获取手机号
		String telephone =  String.valueOf(orderInfo.get("telephone"));
		// 获取套餐ID
		Integer setmealId = Integer.parseInt(String.valueOf(orderInfo.get("setmealId")));
		// 判断所选日期能不能预约
		OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
		if(ObjectUtils.isEmpty(orderSetting)){
			return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
		}

		// 所选日期已经约满，则提示错误信息
		if(orderSetting.getNumber() <= orderSetting.getReservations()){
			return new Result(false,MessageConstant.ORDER_FULL);
		}

		// 判断是不是会员
		Member member = memberDao.findByTelephone(telephone);
		if(ObjectUtils.isEmpty(member)){
		//	如果不是会员，自动完成注册
			//当前用户不是会员，需要添加到会员表
			//member = new Member();
			//member.setName((String) orderInfo.get("name"));
			//member.setPhoneNumber(telephone);
			//member.setIdCard((String) orderInfo.get("idCard"));
			//member.setSex((String) orderInfo.get("sex"));
			//member.setRegTime(new Date());

			member = Member.builder().name((String) orderInfo.get("name"))
					.phoneNumber(telephone)
					.idCard((String) orderInfo.get("idCard"))
					.regTime(new Date())
					.sex((String) orderInfo.get("sex"))
					.build();
			memberDao.add(member);
		} else {
			// 如果是会员，则判断是否重复预约，提示错误信息
			Integer id = member.getId();
			List<Order> orderList = orderDao.findByCondition(new Order(id, date, null, null, setmealId));
            if(!CollectionUtils.isEmpty(orderList)){
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
		}



		// 如果没有重复预约，则新增订单，同时更新已预约人数
		//orderSetting.setReservations(orderSetting.getReservations() + 1);
		//orderSettingDao.editReservationsByOrderDate(orderSetting);


		//在更新前查一下根据版本查数据
		OrderSetting vOrderSetting = orderSettingDao.selectOrderSettingByVersion(orderSetting);

		if (ObjectUtils.isEmpty(vOrderSetting)){

			//查询失败说明 版本问题 抛出自定义的乐观锁异常
			throw new OptimisticLockingFailureException();

		}else {
			//根据日期修改orderSetting表,把预约人数+1
			orderSettingDao.editReservationsByOrderDate(orderSetting);
		}

		Order order = new Order(member.getId(),
				date,
				String.valueOf(orderInfo.get("orderType")),
				Order.ORDERSTATUS_NO,
				setmealId

		);
		orderDao.add(order);

		return new Result(true,MessageConstant.ORDER_SUCCESS,order);
	}

	@Override
	public Map findById(Integer id) throws Exception {
		Map orderDetail = orderDao.findById4Detail(id);
		String orderDate = DateUtils.parseDate2String((Date) orderDetail.get("orderDate"));
		orderDetail.put("orderDate",orderDate);
		return orderDetail;
	}

	@Override
	public List<Map> findSetmealCount() {
		return orderDao.findSetmealCount();
	}
}
